package org.dromara.oce.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.oce.domain.OceTitle;
import org.dromara.oce.domain.OceTitleWrap;
import org.dromara.oce.domain.OceWrapTitle;
import org.dromara.oce.domain.bo.OceTitleWrapBo;
import org.dromara.oce.domain.bo.OceWrapTitleBo;
import org.dromara.oce.domain.qo.OceTitleWrapQo;
import org.dromara.oce.domain.vo.OceTitleVo;
import org.dromara.oce.domain.vo.OceTitleWrapVo;
import org.dromara.oce.mapper.OceTitleMapper;
import org.dromara.oce.mapper.OceTitleWrapMapper;
import org.dromara.oce.mapper.OceWarpTitleMapper;
import org.dromara.oce.service.OceTitleWrapService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 标题包Service业务层处理
 *
 * @author dsbb
 * @date 2025-06-16
 */
@RequiredArgsConstructor
@Service
public class OceTitleWrapServiceImpl extends ServiceImpl<OceTitleWrapMapper,OceTitleWrap> implements OceTitleWrapService {

    private final OceTitleWrapMapper baseMapper;
    private final OceWarpTitleMapper wrapMapper;
    private final OceTitleMapper titleMapper;


    /**
     * 查询标题包
     *
     * @param id 主键
     * @return 标题包
     */
    @Override
    public OceTitleWrapVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询标题包列表
     *
     * @param qo        查询条件
     * @param pageQuery 分页参数
     * @return 标题包分页列表
     */
    @Override
    public TableDataInfo<OceTitleWrapVo> queryPageList(OceTitleWrapQo qo, PageQuery pageQuery) {
        LambdaQueryWrapper<OceTitleWrap> lqw = buildQueryWrapper(qo);
        Page<OceTitleWrapVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的标题包列表
     *
     * @param qo 查询条件
     * @return 标题包列表
     */
    @Override
    public List<OceTitleWrapVo> queryList(OceTitleWrapQo qo) {
        LambdaQueryWrapper<OceTitleWrap> lqw = buildQueryWrapper(qo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<OceTitleWrap> buildQueryWrapper(OceTitleWrapQo qo) {
        LambdaQueryWrapper<OceTitleWrap> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(qo.getName()), OceTitleWrap::getName, qo.getName());
        lqw.orderByDesc(OceTitleWrap::getId);
        return lqw;
    }

    /**
     * 新增标题包
     *
     * @param bo 标题包
     * @return 是否新增成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(OceTitleWrapBo bo) {
        // 检查输入参数
        if (bo == null || CollectionUtils.isEmpty(bo.getTitles())) {
            throw new ServiceException("参数bo或标题列表不能为空");
        }
        OceTitleWrap add = MapstructUtils.convert(bo, OceTitleWrap.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (!flag) {
            return false;
        }
        Long id = add.getId();
        List<String> titles = bo.getTitles();
        try {
            // 批量插入标题
            List<OceTitle> titleList = titles.stream()
                .map(title -> {
                    OceTitle warpTitle = new OceTitle();
                    warpTitle.setType("1");
                    warpTitle.setName(title);
                    return warpTitle;
                })
                .collect(Collectors.toList());

            if (!titleList.isEmpty()) {
                titleMapper.insertBatch(titleList);

                // 获取刚插入的标题ID列表
                List<OceTitle> insertedTitles = titleMapper.selectList(
                    new QueryWrapper<OceTitle>()
                        .in("name", titles)
                        .last("ORDER BY id DESC LIMIT " + titles.size())
                );

                // 批量插入关联关系
                List<OceWrapTitle> wrapTitleList = insertedTitles.stream()
                    .map(insertedTitle -> {
                        OceWrapTitle warp = new OceWrapTitle();
                        warp.setWrapId(id);
                        warp.setTitleId(insertedTitle.getId());
                        return warp;
                    })
                    .collect(Collectors.toList());

                if (!wrapTitleList.isEmpty()) {
                    wrapMapper.insertBatch(wrapTitleList);
                }
            }
            return true;
        } catch (Exception e) {
            // 记录日志
            log.error("插入标题和关联关系失败, wrapId: {}", e);
            throw new RuntimeException("插入标题和关联关系失败", e);
        }
    }

    /**
     * 修改标题包
     *
     * @param bo 标题包
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(OceTitleWrapBo bo) {
        OceTitleWrap update = MapstructUtils.convert(bo, OceTitleWrap.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(OceTitleWrap entity){
    }

    /**
     * 校验并批量删除标题包信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public List<OceTitleVo> queryTitleList(Long id) {
        return baseMapper.queryTitleList(id);
    }

    @Override
    public Boolean insertWrapTitle(OceWrapTitleBo bo) {
        List<OceWrapTitle> list = new ArrayList<>();
        List<Long> ids = bo.getIds();
        Long wrapId = bo.getWrapId();
        for (int i = 0; i < ids.size(); i++) {
            OceWrapTitle warpTitle = new OceWrapTitle();
            warpTitle.setWrapId(wrapId);
            warpTitle.setTitleId(ids.get(i));
            list.add(warpTitle);
        }
        return wrapMapper.insertBatch(list);
    }

    @Override
    public Boolean updateWrapTitle(OceWrapTitleBo bo) {
        wrapMapper.deleteByWrapId(bo.getWrapId());
        List<OceWrapTitle> list = new ArrayList<>();
        List<Long> ids = bo.getIds();
        Long wrapId = bo.getWrapId();
        for (int i = 0; i < ids.size(); i++) {
            OceWrapTitle warpTitle = new OceWrapTitle();
            warpTitle.setWrapId(wrapId);
            warpTitle.setTitleId(ids.get(i));
            list.add(warpTitle);
        }
        return wrapMapper.insertBatch(list);
    }

    @Override
    public Boolean deleteWrapTitle(OceWrapTitleBo bo) {
        return wrapMapper.deleteWrapTitle(bo.getWrapId(),bo.getIds());
    }
}
